﻿using System;
using System.Collections.ObjectModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

using Sunyi.Project.WebPoint.BusinessLogic;
using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.Configuration;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.Resource;
using Sunyi.Project.WebPoint.WebControl;

namespace ActivitySystem.Web.Admin
{
    public partial class UserEdit : WebPointPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    InitializeControlValues();

                    if (!string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.UserId]))
                    {
                        Guid userId = new Guid(Request.Params[WebPointGlobalConstant.UserId]);
                        BindUser(userId);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionHandler.Handle(this, ex);
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string validationMessage = ValidateParameters();

            if (!string.IsNullOrEmpty(validationMessage))
            {
                this.ShowClientMessage(validationMessage);
                return;
            }

            User user = null;
            bool isUserExist = false;
            UserManager userManager = new UserManager();

            try
            {
                if (!string.IsNullOrEmpty(tbxId.Text))
                {
                    user = userManager.Select(new Guid(tbxId.Text));
                    if (user != null) { tbxUserName.Text = user.UserName; isUserExist = true; }
                }
                else
                {
                    user = userManager.SelectByName(tbxUserName.Text.Trim());

                    if (user == null)
                    {
                        user = new User();
                        user.Id = Guid.NewGuid();
                        user.UserName = tbxUserName.Text;
                        user.Password = SystemConfiguration.WebSite[WebPointGlobalConstant.UserDefaultPassword];
                    }
                    else
                    {
                        isUserExist = true;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
                return;
            }

            user.UserId = tbxUserId.Text;
            user.Mail = tbxMail.Text;
            user.Department = tbxDepartment.Text;
            user.IsActive = Boolean.Parse(ddlStatus.SelectedValue);
            if (user.Password != tbxPassword.Text) user.Password = EncrpytionHelper.EncrpytByMD5(tbxPassword.Text.Trim());

            Collection<Guid> newRoles = new Collection<Guid>();
            Collection<Guid> removedRoles = new Collection<Guid>();
            foreach (ListItem item in cblRole.Items) { if (item.Selected) newRoles.Add(new Guid(item.Value)); }
            foreach (var roleId in user.Roles) { if (!newRoles.Contains(roleId)) removedRoles.Add(roleId); }

            user.Roles.Clear();
            foreach (var roleId in newRoles) { if (!user.Roles.Contains(roleId)) user.Roles.Add(roleId); }

            try
            {
                if (isUserExist)
                {
                    TransactionHelper.ProcessTransaction(delegate { userManager.Save(user); if (SystemConfiguration.PersonnelServiceEnabled) userManager.UploadUserInfo(user, removedRoles); });

                    AuditLogger.Write(AuditLogOperationCode.Update, this.GetType().Name, user);

                    this.ShowClientMessage(WebResource.OP_UpdateUserSuccessful);
                    this.ClientRedirect(string.Format(WebPointWebCommon.RedirectUrlFormatRead, this.Request.Path, WebPointGlobalConstant.UserId, user.Id));
                }
                else
                {
                    TransactionHelper.ProcessTransaction(delegate { userManager.Insert(user); if (SystemConfiguration.PersonnelServiceEnabled) userManager.UploadUserInfo(user, removedRoles); });

                    AuditLogger.Write(AuditLogOperationCode.Create, this.GetType().Name, user);

                    this.ShowClientMessage(WebResource.OP_CreateUserSuccessful);
                    this.ClientRedirect(string.Format(WebPointWebCommon.RedirectUrlFormatRead, this.Request.Path, WebPointGlobalConstant.UserId, user.Id));
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
            }
        }

        #region Private Method

        private void InitializeControlValues()
        {
            tbxMail.Text = SystemConfiguration.WebSite[WebPointGlobalConstant.UserDefaultMailPostfix];
            tbxDepartment.Text = SystemConfiguration.WebSite[WebPointGlobalConstant.UserDefaultDepartment];
            tbxPassword.Text = SystemConfiguration.WebSite[WebPointGlobalConstant.UserDefaultPassword];

            BindRole();

            if (!string.IsNullOrEmpty(SystemConfiguration.WebSite[WebPointGlobalConstant.UserDefaultRole]))
            {
                string[] roleNames = SystemConfiguration.WebSite[WebPointGlobalConstant.UserDefaultRole].Split(WebPointGlobalConstant.Comma[0]);

                foreach (string roleName in roleNames)
                {
                    foreach (ListItem item in cblRole.Items)
                    {
                        if (item.Text == roleName)
                        {
                            item.Selected = true;
                            break;
                        }
                    }
                }
            }

            sp_warning.Visible = false;
            if (!string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.UserId]))
            {
                tbxUserName.Enabled = false;

                if (SystemConfiguration.PersonnelServiceEnabled)
                {
                    sp_warning.Visible = true;
                    tbxId.Enabled = false;
                    tbxUserId.Enabled = false;
                    tbxMail.Enabled = false;
                    tbxDepartment.Enabled = false;
                }
            }
        }

        private void BindRole()
        {
            RoleManager roleManager = new RoleManager();
            Collection<Role> roles = roleManager.SelectAll();

            foreach (Role role in roles)
            {
                if (role.IsActive) cblRole.Items.Add(new ListItem(role.RoleName, role.Id.ToString()));
            }
        }

        private void BindUser(Guid userId)
        {
            UserManager userManager = new UserManager();
            User user = userManager.Select(userId);

            if (user != null)
            {
                tbxId.Text = user.Id.ToString();
                tbxUserId.Text = user.UserId;
                tbxUserName.Text = user.UserName;
                tbxPassword.Text = user.Password;
                tbxMail.Text = user.Mail;
                tbxDepartment.Text = user.Department;
                WebPointWebCommon.SetItemSelected(ddlStatus, user.IsActive.ToString());

                foreach (ListItem item in cblRole.Items)
                {
                    Guid roleId = new Guid(item.Value);

                    item.Selected = user.Roles.Contains(roleId);
                }
            }
        }

        private string ValidateParameters()
        {
            StringBuilder sb = new StringBuilder();

            if (string.IsNullOrEmpty(tbxUserId.Text))
            {
                tbxUserId.BackColor = WebControlCommon.WarningBackColor;
                sb.Append(string.Format(WebResource.FieldValueIsNull, tbxUserId.ID) + WebPointGlobalConstant.WebEnter);
            }
            else
            {
                tbxUserId.BackColor = WebControlCommon.DefaultControlBackColor;
            }

            if (string.IsNullOrEmpty(tbxUserName.Text))
            {
                tbxUserName.BackColor = WebControlCommon.WarningBackColor;
                sb.Append(string.Format(WebResource.FieldValueIsNull, tbxUserName.ID) + WebPointGlobalConstant.WebEnter);
            }
            else
            {
                tbxUserName.BackColor = WebControlCommon.DefaultControlBackColor;
            }

            if (string.IsNullOrEmpty(tbxPassword.Text))
            {
                tbxPassword.BackColor = WebControlCommon.WarningBackColor;
                sb.Append(string.Format(WebResource.FieldValueIsNull, tbxPassword.ID) + WebPointGlobalConstant.WebEnter);
            }
            else
            {
                tbxPassword.BackColor = WebControlCommon.DefaultControlBackColor;
            }

            if (string.IsNullOrEmpty(tbxMail.Text))
            {
                tbxMail.BackColor = WebControlCommon.WarningBackColor;
                sb.Append(string.Format(WebResource.FieldValueIsNull, tbxMail.ID) + WebPointGlobalConstant.WebEnter);
            }
            else
            {
                tbxMail.BackColor = WebControlCommon.DefaultControlBackColor;
            }

            return sb.ToString();
        }

        #endregion

        #region WebPointPage Member

        protected override void ApplyPermission()
        {
            if (!string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.UserId]) && !this.HasPermission(PermissionType.Update))
            {
                btnSubmit.Visible = false;
            }

            if (string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.UserId]) && !this.HasPermission(PermissionType.Create))
            {
                btnSubmit.Visible = false;
            }

            if (this.RequestPermissionType == PermissionType.Read)
            {
                btnSubmit.Visible = false;
            }
        }

        #endregion
    }
}